<?php

/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: ShoppingcartController.php 3075 2010-05-26 15:41:59Z quanvo $
 */

class Shoppingcart_ShoppingcartController extends Zend_Controller_Action {	
	
	private $_timeChecked;
	
	public function init(){
		$this->_timeChecked = 60*60*24*2;
	}

    /**
    * List of shopping cart
    * @return void
    **/
    public function listAction(){
        $request = $this->getRequest();
        $lang = $request->getParam('lang');
		$this->view->assign('lang', $lang);
         
        /**
        * Get cart id from cookie
        **/
        $card_id = $this->buildCookie();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $this->view->assign('cartDao', $cartDao);

        /**
        * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);
        
        /**
         * Product models access to data
         */
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
         * Set current language for cart modles
        **/
        $cartDao->setLang($lang);

        /**
         * Get cart detail info
        **/
        $cartDetails = $cartDao->getDetailById($card_id);
        $this->view->assign('cartDetails', $cartDetails);
        
        /**
    	 * Tính tổng số lượng từng sản phẩm lưu vào array
    	 * @author quanvo
    	 */
    	$arrPQty = array();
    	foreach($cartDetails as $itemRow){
    		$cart_quantity = (!$itemRow->cart_parent_id)?$itemRow->cart_quantity:0;
    		$product_id	   = $itemRow->product_id;
    		
    		/**
    		 * $$variable: cách khai báo biến của biến
    		 */
    		$variable = 'variable'.$product_id;    		
    		@$$variable += $cart_quantity;
    		
    		/**
    		 * Gán giá trị được tạo ra vào array
    		 */
    		$arrPQty[$product_id] = $$variable;
    	}

        /**
        *Build array enterprise
        **/
        $arrayEnterpriseId = array();
        $arrayQuantity = array();
        $arrOverQty = array();
        $accept = true; //Kiểm tra ẩn/hiện link thanh toán  
        //print_r($cartDetails);   //die;   
        foreach($cartDetails as $d_cart){
            $product = null;
            if(is_numeric($d_cart->product_id)){
                $product = $cartDao->getProductById($d_cart->product_id);                
                
                /**
            	 * Kiểm tra số lượng sản phẩm trong cart vượt quá số lượng sản phẩm hiện có trong database
            	 * @author quanvo
            	 */            	
                
                $variable = 'variable'.$d_cart->product_id;
                $$variable = $d_cart->product_id;
                
                $itemRow = $arrPQty[$d_cart->product_id];
        		if($product->product_quantity_mode != 'infinity' && $product->product_quantity < $itemRow){
        			$arrInfo = array(
        				'product_quantity' => $product->product_quantity,
        				'cart_detail_id' => $d_cart->id,
        				'qtyExisted' => $itemRow
        			);        			
        			if(!$d_cart->cart_parent_id){
        				$arrOverQty[$d_cart->product_id] = $arrInfo;  
        			}
        			$accept = false;
        		}
            }

            if($product){
                $arrayEnterpriseId[$product->enterprise_id] = $product->enterprise_id;
            }

            /**
            * Check loop product and sum quantity of this product
            **/
            $pid = $product->product_id;
            $cartQ = $d_cart->cart_quantity;
            @$$pid += $cartQ;
            $arrayQuantity[$product->product_id] = $$pid;
        }
        $this->view->assign('arrayEnterpriseId', $arrayEnterpriseId);
        $this->view->assign('arrOverQty', $arrOverQty);
        $this->view->assign('accept', $accept);

        /**
         * Get product info foreach cart detail id
         * $arrProducts : Store product info for cart
         * $shipping_price: Store toal shipping of cart
         * $total : Total amount fo cart
        **/
        $arrProductsSorted = array();
        $shipping_priceSorted = array();
        $subtotalSorted = array();
        $arrAllAtValSorted = array();

        $arrayCartSorted = array();
        $arrayEnterpriseInfo = array();
        foreach($arrayEnterpriseId as $r_id){

            $arraySubCartSorted = array();

            /**
            * Get product info foreach cart detail id
            * $arrProducts : Store product info for cart
            * $shipping_price: Store toal shipping of cart
            * $total : Total amount fo cart
            **/
            $arrProducts = array();
            $shipping_price = 0;
            $subtotal = 0;
            $arrAllAtVal = null;

            foreach($cartDetails as $d_cart){
                $product = null;
                if(is_numeric($d_cart->product_id)){
                    $product = $cartDao->getProductById($d_cart->product_id);
                }

                /**
                * Check isset product info for cart id again
                * $p_name: Name of product
                * $p_image: Image of product
                * $p_price: Price of product
                * $p_currency: Currency of product
                * $total_price: $p_price * cart_quantity
                **/
                $p_name = null;
                $p_slug = null;
                $p_image = null;
                $p_price = 0;
                $p_currency = null;
                $total_price = 0;
                $e_name = null;
                $e_id = null;
                $c_slug = null;
                $c_name = null;
                $c_id = null;
                if($product){

                    /**
                    * Build array product follow enterprise
                    **/
                    if($r_id == $product->enterprise_id){
                        $arraySubCartSorted[] = $d_cart;

                        $p_name     = trim($product->product_content_name)?$product->product_content_name:$product->product_admin_name;
                        $p_slug     = $product->slug;
                        $p_price    = $product->product_price;
                        $p_currency = $product->product_price_currency;
                        $p_image = $product->getImage();

                        /**
                        * Get total_price
                        **/
                        if(!$d_cart->cart_parent_id){
                        	$total_price = $p_price*$d_cart->cart_quantity;
                        }

                        /**
                        * Get shipping price
                        **/
                        if(!$d_cart->cart_parent_id){
	                        if(isset($arrayQuantity[$d_cart->product_id])){
	                            $quantity = $arrayQuantity[$d_cart->product_id];
	                            $shipping_price += $product->product_shipping_price_1+$quantity*$product->product_shipping_price_2;
	                            unset($arrayQuantity[$d_cart->product_id]);
	                        }
                        }

                        /**
                        * Get enterprise follow product
                        **/
                        $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                        $e_name = $objEnterprise->company_name_en;
                        $e_id   = $objEnterprise->id;

                        /**
                        * Get category follow product
                        **/
                        $category_id = substr(substr($product->category_id,1),0,-1);
                        $objCategory = $categoryDao->getById($category_id);
                        $c_slug = $objCategory->slug;
                        $c_name = $objCategory->category_admin_name;
                        $c_id = $objCategory->category_id;
                    }
                }

                $arrSubProduct['p_name'] = $p_name;
                $arrSubProduct['p_slug'] = $p_slug;
                $arrSubProduct['p_image'] = $p_image;
                $arrSubProduct['p_price'] = $p_price;
                $arrSubProduct['p_currency'] = $p_currency;
                $arrSubProduct['total_price'] = $total_price;
                $arrSubProduct['e_name'] = $e_name;
                $arrSubProduct['e_id']   = $e_id;
                $arrSubProduct['c_slug'] = $c_slug;
                $arrSubProduct['c_name'] = $c_name;
                $arrSubProduct['c_id']   = $c_id;

                /**
                * Get total amount
                **/
                $subtotal += $total_price;

                /**
                * Create array product info
                **/
                $arrProducts[$d_cart->id] = $arrSubProduct;

                /**
                * Get attribute and value info for product
                **/
                $arrAtValId = Zend_Json::decode($d_cart->product_attribute_value_id_chain);
                if($arrAtValId){
                    $arrAtVal = array();
                    $htmlAttVal = '<div>';
                    foreach($arrAtValId as $key=>$row){
                        $attriubte = $attributeDao->getFEById($key);
                        $value = $valueDao->getFEById($row);
                        $attName = ($attriubte->attribute_type_content_name)?$attriubte->attribute_type_content_name:$attriubte->attribute_type_admin_name;
                        $valName = ($value->value_content_name)?$value->value_content_name:$value->value_type_name;
                        $htmlAttVal .= "<div style='display:table; width:100%;'><div style='float:left; width:50%; text-align:left;'><b>{$attName}:</b></div><div style='float:left; width:50%; text-align:left;'>{$valName}</div></div>";
                    }
                    $arrAllAtVal[$d_cart->id] = $htmlAttVal.'</div>';
                }
            }
            $arrayEnterpriseInfo[$r_id] = $objEnterprise;
            $arrProductsSorted[$r_id] = $arrProducts;
            $shipping_priceSorted[$r_id] = $shipping_price;
            $subtotalSorted[$r_id] = $subtotal;
            $arrAllAtValSorted[$r_id] = $arrAllAtVal;
            $arrayCartSorted[$r_id] = $arraySubCartSorted;
        }
        $this->view->assign('arrayEnterpriseInfo', $arrayEnterpriseInfo);
        $this->view->assign('arrProductsSorted', $arrProductsSorted);
        $this->view->assign('shipping_priceSorted', $shipping_priceSorted);
        $this->view->assign('subtotalSorted', $subtotalSorted);
        $this->view->assign('arrAllAtValSorted', $arrAllAtValSorted);
        $this->view->assign('arrayCartSorted', $arrayCartSorted);
        
        if($request->isPost()){
            $cart_id	 = $request->getPost('cart_id');
            $cart_remove = $request->getPost('cart_remove');

            /**
             * Update cart detail quantity
            **/
            if($cart_id){
            	
            	/**
            	 * Thự hiện update cart nếu thỏa điều trên
            	 * @author quanvo
            	 */
                foreach($cart_id as $id){
                    $cart_quantity = $request->getPost('cart_quantity_'.$id);
                    if($cart_quantity > 0){
                        $cart = new Shoppingcart_Models_Cart(array(
                                'id'            => $id,
                                'cart_quantity' => $cart_quantity,
                        ));
                        $cartDao->updateQuantiy($cart);
                    }else{
                        $cartDao->deleteDetail($id);
                    }
                }
            }

            /**
             * Delete cart detail
            **/
            if($cart_remove){
                foreach($cart_remove as $r_id){
                    $cartDao->deleteDetail($r_id);
                }
            }
            /**
            * Redirect cart list
            **/
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_list'));
        }
    }

    /**
    * Add item to cart
    * @return void
    **/
    public function addAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        //$this->_helper->getHelper('viewRenderer')->setNoRender();

        $request    = $this->getRequest();
        $product_id = $request->getParam('product_id');
        $lang = $request->getParam('lang');

        /**
        * Get cart id from cookie
        **/
        $cart_id = $this->buildCookie();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $cartDao->setLang($lang);

        /**
         * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        $flag  = false;

        /**
         * Set default value for field
        **/
        $cart_quantity = 1;
        $product_attribute_value_id_chain = null;
        $cart_detail_id = null;
        if($request->isPost()){
            $arrId = $request->getPost('attribute_type_id');
            $cart_quantity = ($request->getPost('quantity')>0)?$request->getPost('quantity'):1;
            $cart_detail_id = ($request->getPost('cart_detail_id')>0)?$request->getPost('cart_detail_id'):null;
			
            /**
            * Get default attribute and value for product
            **/
            $attributes = $attributeDao->getAttOfPro($product_id);
            if(count($attributes) > 0){
                $arrAttValue = array();
                foreach($attributes as $attribute){
                    $values = $valueDao->values($attribute->value_type_id_chain);
                    if(count($values) > 0){
                        $arrAttValue[$attribute->attribute_type_id] = $values[0]->value_type_id;
                    }
                }
                $product_attribute_value_id_chain = Zend_Json::encode($arrAttValue);
            }

            /**
            * check $arrId exist
            **/
            if($arrId){
                $arrAttValue = array();
                foreach($arrId as $id){
                    $att_value = $request->getPost('att_value_'.$id);
                    if($att_value){
                        $arrAttValue[$id] = $att_value;
                    }
                }
                $product_attribute_value_id_chain = Zend_Json::encode($arrAttValue);
            }

            if(null == $cart_detail_id){
                $cart = new Shoppingcart_Models_Cart(array(
                                'cart_id'                          => $cart_id,
                                'product_id'                       => $product_id,
                                'cart_quantity'                    => $cart_quantity,
                                'product_attribute_value_id_chain' => $product_attribute_value_id_chain,
                                'cart_parent_id'                   => null,
                ));
                $latestId = $cartDao->addDetail($cart);
                
                if($latestId){                	
                	$this->view->assign('latestId', $latestId);
                	
                	/**
		             * Lấy thông tin chi tiết của sản phẩm
		             * Kiểm tra sản phẩm được add vào có phải là bundle
		             * @author 
		             */
		            $productInfo = $cartDao->getProductById($product_id);
		            if($productInfo->product_bundle == 1){
		            	$strProductIds = substr(substr($productInfo->product_product_id_chain,1),0,-1);
		            	$arrProductIds = ($strProductIds)?explode(',', $strProductIds):null;
		            	if($arrProductIds){            		
		            		$arrProductHandler = array_unique($arrProductIds);
		            		foreach ($arrProductHandler as $rowId){
		            			
		            			/**
					            * Get default attribute and value for product
					            **/
					            $attributes = $attributeDao->getAttOfPro($rowId);
					            $bundleValueChild = null;
					            if(count($attributes) > 0){
					                $arrAttValue = array();
					                foreach($attributes as $attribute){
					                    $values = $valueDao->values($attribute->value_type_id_chain);
					                    if(count($values) > 0){
					                        $arrAttValue[$attribute->attribute_type_id] = $values[0]->value_type_id;
					                    }
					                }
					                $bundleValueChild = Zend_Json::encode($arrAttValue);
					            }
					            $countQty = substr_count($strProductIds, $rowId);
				                $cartChild = new Shoppingcart_Models_Cart(array(
				                        'cart_id'                          => $cart_id,
				                        'product_id'                       => $rowId,
				                        'cart_quantity'                    => $countQty,
				                        'product_attribute_value_id_chain' => $bundleValueChild,
				                        'cart_parent_id'                   => $latestId,
				                ));
				                $cartDao->addDetail($cartChild);
		            		}
		            		
		            	}
		            }
                	
                    /**
                     * Kiểm tra nếu sản phẩm có thuộc tính thì tạo cái giá cho đường dẫn tới thay đổi chi tiết
                     */
                    if($product_attribute_value_id_chain){

                        /**
                        * Get product info
                        **/
                        $product = $cartDao->getProductById($product_id);

                        /**
                        * Get enterprise follow product
                        **/
                        $objEnterprise = $enterpriseDao->getById($product->enterprise_id);

                        /**
                        * Get category follow product
                        **/
                        $category_id = substr(substr($product->category_id,1),0,-1);
                        $objCategory = $categoryDao->getById($category_id);

                        /**
                         * Array url info
                        **/
                        $arrPEC = array(
                            'p_id' => $product_id,
                            'p_slug' => $product->slug,
                            'p_name' => $product->product_admin_name,
                            'e_name' => $objEnterprise->company_name_en,
                            'e_id' => $objEnterprise->id,
                            'c_slug' => $objCategory->slug,
                            'c_name' => $objCategory->category_admin_name,
                            'c_id' => $objCategory->category_id
                        );
                        $this->view->assign('arrPEC', $arrPEC);
                        $flag = true;
                    }
                }
            }
            else{
                $cart = new Shoppingcart_Models_Cart(array(
                                'id'                               => $cart_detail_id,
                                'product_attribute_value_id_chain' => $product_attribute_value_id_chain,
                ));
                $cartDao->updateDetail($cart);
            }
        }
        $this->view->assign('flag', $flag);
        /**$this->getResponse()->setBody($result);*/
    }

    public function checkOutAction(){
        $request = $this->getRequest();

        $auth = Zend_Auth::getInstance();
        $user = $auth->getIdentity();
        
        //Check this account is allow purchase
        if(!Core_Services_RuleChecker::isAllowed('checkout', 'shoppingcart', 'shoppingcart') && $user){
        	$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_list'));	
        }

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);

        /**
        * Customer models access to data
        **/
        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        /**
         * User models access to data
        **/
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * User enterprise models access to data
        **/
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
         * Order models access to data
        **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
         * Assignment models access to data
        **/
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        $customer = null;
        $flag = false;
        if($user){
            $customer = $customerDao->getCustomer($user->user_id);

            /**
             * Check order of user is exist with status diff close
            **/
            $orders = $orderDao->getOByU($user->user_id);
            if(count($orders) > 0){
                foreach($orders as $order){
                    $process = $assignmentDao->getPSById($order->process_id);
                    if($process->code != 'close'){
                        $flag = true;
                        break;
                    }
                }
            }else{
                $flag = false;
            }
        }
        $this->view->assign('user', $user);
        $this->view->assign('customer', $customer);
        $this->view->assign('flag', $flag);

        if($request->isPost()){
            $full_name        = $request->getPost('full_name');
            $username         = $request->getPost('email');
            $email            = $request->getPost('email');
            $address          = $request->getPost('address');
            $city             = $request->getPost('city');
            $tel              = $request->getPost('tel');
            $shipping_name    = $request->getPost('shipping_name');
            $shipping_email   = $request->getPost('shipping_email');
            $shipping_address = $request->getPost('shipping_address');
            $shipping_city    = $request->getPost('shipping_city');
            $shipping_tel     = $request->getPost('shipping_tel');

            $customer = new Bizprofile_Models_Customer(array(
                    'customer_address'  => $address,
                    'customer_city'     => $city,
                    'customer_tel'      => $tel,
                    'shipping_name'     => $shipping_name,
                    'shipping_email'    => $shipping_email,
                    'shipping_address'  => $shipping_address,
                    'shipping_city'     => $shipping_city,
                    'shipping_tel'      => $shipping_tel,
            ));
            if($user){            	
                $customer->user_id = $user->user_id;

                $userInfo = new Core_Models_User(array(
                        'user_name' => $user->user_name,
                        'full_name' => $full_name,
                        'email'     => $user->email,
                        'role_id'   => $user->role_id,
                        'user_id'   => $user->user_id
                ));
                /**
                 * Update user
                **/
                $userDao->update($userInfo);

                /**
                 * Update user session
                **/
                $user->full_name = $full_name;

                /**
                 * Update customer
                **/
                if($customerDao->getCustomer($user->user_id)){
                	$customerDao->updateCustomer($customer);	
                }
                else{
                	$customerDao->add($customer);	
                }
            }
            else
            {
                $password  = $this->generatePassword();
                
                $role = $userAccountDao->getRoleByName('nguoi tieu dung');
                $roleId = $role->role_id;
                $userInfo = new Core_Models_User(array(
                    'user_name'      => $username,
                    'password'       => $password,
                    'full_name'      => $full_name,
                    'email'          => $email,
                    'is_active'      => 1,
                    'created_date'   => date('Y-m-d H:i:s'),
                    'logged_in_date' => null,
                    'is_online'      => 0,
                    'role_id'        => $roleId,
                ));
                $id = $userDao->add($userInfo);

                if($id){                
                    /**
                    * Add customer info follow user
                    **/
                    $customer->user_id = $id;
                    $customerDao->add($customer);
                    
                    /**
	                * Send email -thong bao password tu dong tao
	                */
	                $mailContent1 = $this->view->translator("user_send_pass_content_mail");
	                $mailContent = $this->view->translator("user_send_pass_content_mail1");
	                $mailContent .= sprintf($this->view->translator("user_send_pass_content_mail2"), $username, $password);
	                $mailContent .= $this->view->translator("user_send_pass_content_mail3");
					
	                $from = "info@kinhdoanhdientu.vn";
	                $from_name = "kinhdoanhdientu.vn";
	               	$to = "{$email}";
	                $bcc = "quan.vo@startech.vn";
	                $content = $mailContent;
	                $subject = $this->view->translator('user_send_pass_subject');
	                $transport = Mail_Services_Mailer::getMailTransport();
	                $mail = new Zend_Mail('utf-8');
	                
	                $mail->setFrom($from, $from_name)
	                    ->addTo($to)
	                    ->addBcc($bcc)
	                    ->setSubject($subject)
	                    ->setBodyHtml($content)
	                    ->send($transport);

                    /**
                     * login when register successfull
                    **/
                    $auth     = Zend_Auth::getInstance();
                    $username = $username;
                    $password = $password;
                    $adapter  = new Bizprofile_Services_Auth($username, $password);
                    $result   = $auth->authenticate($adapter);
                    switch ($result->getCode()) {
                        /**
                        * Found user, but the account has not been activated
                        */
                        case Bizprofile_Services_Auth::NOT_ACTIVE:
                            echo 'NOT_ACTIVE';die;
                            $this->_helper->getHelper('FlashMessenger')
                                ->addMessage($this->view->translator('auth_login_user_not_activated'));
                            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
                            break;

                        /**
                        * Logged in successfully
                        */
                        case Bizprofile_Services_Auth::SUCCESS:
                            $user = $auth->getIdentity();
                            Tomato_Hook_Registry::getInstance()->executeAction('Bizprofile_Auth_Login_LoginSuccess', $user);
                            break;

                        /**
                        * Not found
                        */
                        case Bizprofile_Services_Auth::FAILURE:
                        default:
                            echo 'FAILURE';die;
                            $this->_helper->getHelper('FlashMessenger')
                                ->addMessage($this->view->translator('auth_login_failure'));
                            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
                            break;
                    }
                }
            }

            /**
            * Redirect
            **/
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_review'));
        }
    }

    public function reviewAction(){
        $request = $this->getRequest();
        $lang = $request->getParam('lang');
        $this->view->assign('lang', $lang);
        
        $auth = Zend_Auth::getInstance();
        $user = $auth->getIdentity();
        //Check this account is allow purchase
        if(!Core_Services_RuleChecker::isAllowed('checkout', 'shoppingcart', 'shoppingcart') && $user){
        	$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_list'));	
        }

        /**
        * Get cart id from cookie
        **/
        $card_id = $this->buildCookie();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $this->view->assign('cartDao', $cartDao);

        /**
        * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        $customerDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getCustomerDao();
        $customerDao->setDbConnection($conn);

        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
         * Set current language for cart modles
        **/
        $cartDao->setLang($lang);

        /**
         * Get cart detail info
        **/
        $cartDetails = $cartDao->getDetailById($card_id);
        $this->view->assign('cartDetails', $cartDetails);
        
        /**
    	 * Tính tổng số lượng từng sản phẩm lưu vào array
    	 * @author quanvo
    	 */
    	$arrPQty = array();
    	foreach($cartDetails as $itemRow){
    		$cart_quantity = (!$itemRow->cart_parent_id)?$itemRow->cart_quantity:0;
    		$product_id	   = $itemRow->product_id;
    		
    		/**
    		 * $$variable: cách khai báo biến của biến
    		 */
    		$variable = 'variable'.$product_id;
    		@$$variable += $cart_quantity;
    		
    		/**
    		 * Gán giá trị được tạo ra vào array
    		 */
    		$arrPQty[$product_id] = $$variable;
    	}        

        /**
        *Build array enterprise
        **/
        $arrayEnterpriseId = array();
        $arrayQuantity = array();
        foreach($cartDetails as $d_cart){
            $product = null;
            if(is_numeric($d_cart->product_id)){
                $product = $cartDao->getProductById($d_cart->product_id);
                
                /**
            	 * Kiểm tra số lượng sản phẩm trong cart vượt quá số lượng sản phẩm hiện có trong database
            	 * @author quanvo
            	 */            	
                
                $variable = 'variable'.$d_cart->product_id;
                $$variable = $d_cart->product_id;
                
                $itemRow = $arrPQty[$d_cart->product_id];
        		if($product->product_quantity_mode != 'infinity' && $product->product_quantity < $itemRow){
        			/**
		            * Redirect cart list
		            **/
		            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_list'));        			
        		}
            }

            if($product){
                $arrayEnterpriseId[$product->enterprise_id] = $product->enterprise_id;
            }

            /**
            * Check loop product and sum quantity of this product
            **/
            $pid = $product->product_id;
            $cartQ = $d_cart->cart_quantity;
            @$$pid += $cartQ;
            $arrayQuantity[$product->product_id] = $$pid;
        }
        $this->view->assign('arrayEnterpriseId', $arrayEnterpriseId);

        /**
         * Get product info foreach cart detail id
         * $arrProducts : Store product info for cart
         * $shipping_price: Store toal shipping of cart
         * $total : Total amount fo cart
        **/
        $arrProductsSorted = array();
        $shipping_priceSorted = array();
        $subtotalSorted = array();
        $arrAllAtValSorted = array();

        $arrayCartSorted = array();
        $arrayEnterpriseInfo = array();
        foreach($arrayEnterpriseId as $r_id){

            $arraySubCartSorted = array();

            /**
            * Get product info foreach cart detail id
            * $arrProducts : Store product info for cart
            * $shipping_price: Store toal shipping of cart
            * $total : Total amount fo cart
            **/
            $arrProducts = array();
            $shipping_price = 0;
            $subtotal = 0;
            $arrAllAtVal = null;

            foreach($cartDetails as $d_cart){
                $product = null;
                if(is_numeric($d_cart->product_id)){
                    $product = $cartDao->getProductById($d_cart->product_id);
                }

                /**
                * Check isset product info for cart id again
                * $p_name: Name of product
                * $p_image: Image of product
                * $p_price: Price of product
                * $p_currency: Currency of product
                * $total_price: $p_price * cart_quantity
                **/
                $p_name = null;
                $p_slug = null;
                $p_image = null;
                $p_price = 0;
                $p_currency = null;
                $total_price = 0;
                $e_name = null;
                $e_id = null;
                $c_slug = null;
                $c_name = null;
                $c_id = null;
                if($product){

                    /**
                    * Build array product follow enterprise
                    **/
                    if($r_id == $product->enterprise_id){
                        $arraySubCartSorted[] = $d_cart;

                        $p_name     = trim($product->product_content_name)?$product->product_content_name:$product->product_admin_name;
                        $p_slug     = $product->slug;
                        $p_price    = $product->product_price;
                        $p_currency = $product->product_price_currency;
						$p_image = $product->getImage();

                        /**
                        * Get total_price
                        **/
                        if(!$d_cart->cart_parent_id){
                        	$total_price = $p_price*$d_cart->cart_quantity;
                        }

                        /**
                        * Get shipping price
                        **/
                        if(!$d_cart->cart_parent_id){
	                        if(isset($arrayQuantity[$d_cart->product_id])){
	                            $quantity = $arrayQuantity[$d_cart->product_id];
	                            $shipping_price += $product->product_shipping_price_1+$quantity*$product->product_shipping_price_2;
	                            unset($arrayQuantity[$d_cart->product_id]);
	                        }
                        }

                        /**
                        * Get enterprise follow product
                        **/
                        $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                        $e_name = $objEnterprise->company_name_en;
                        $e_id   = $objEnterprise->id;

                        /**
                        * Get category follow product
                        **/
                        $category_id = substr(substr($product->category_id,1),0,-1);
                        $objCategory = $categoryDao->getById($category_id);
                        $c_slug = $objCategory->slug;
                        $c_name = $objCategory->category_admin_name;
                        $c_id = $objCategory->category_id;
                    }
                }

                $arrSubProduct['p_name'] = $p_name;
                $arrSubProduct['p_slug'] = $p_slug;
                $arrSubProduct['p_image'] = $p_image;
                $arrSubProduct['p_price'] = $p_price;
                $arrSubProduct['p_currency'] = $p_currency;
                $arrSubProduct['total_price'] = $total_price;
                $arrSubProduct['e_name'] = $e_name;
                $arrSubProduct['e_id']   = $e_id;
                $arrSubProduct['c_slug'] = $c_slug;
                $arrSubProduct['c_name'] = $c_name;
                $arrSubProduct['c_id']   = $c_id;

                /**
                * Get total amount
                **/
                $subtotal += $total_price;

                /**
                * Create array product info
                **/
                $arrProducts[$d_cart->id] = $arrSubProduct;

                /**
                * Get attribute and value info for product
                **/
                $arrAtValId = Zend_Json::decode($d_cart->product_attribute_value_id_chain);
                if($arrAtValId){
                    $arrAtVal = array();
                    $htmlAttVal = '<div>';
                    foreach($arrAtValId as $key=>$row){
                        $attriubte = $attributeDao->getFEById($key);
                        $value = $valueDao->getFEById($row);
                        $attName = ($attriubte->attribute_type_content_name)?$attriubte->attribute_type_content_name:$attriubte->attribute_type_admin_name;
                        $valName = ($value->value_content_name)?$value->value_content_name:$value->value_type_name;
                        $htmlAttVal .= "<div style='display:table; width:100%;'><div style='float:left; width:50%; text-align:left;'><b>{$attName}:</b></div><div style='float:left; width:50%; text-align:left;'>{$valName}</div></div>";
                    }
                    $arrAllAtVal[$d_cart->id] = $htmlAttVal.'</div>';
                }
            }
            $arrayEnterpriseInfo[$r_id] = $objEnterprise;
            $arrProductsSorted[$r_id] = $arrProducts;
            $shipping_priceSorted[$r_id] = $shipping_price;
            $subtotalSorted[$r_id] = $subtotal;
            $arrAllAtValSorted[$r_id] = $arrAllAtVal;
            $arrayCartSorted[$r_id] = $arraySubCartSorted;
        }
        $this->view->assign('arrayEnterpriseInfo', $arrayEnterpriseInfo);
        $this->view->assign('arrProductsSorted', $arrProductsSorted);
        $this->view->assign('shipping_priceSorted', $shipping_priceSorted);
        $this->view->assign('subtotalSorted', $subtotalSorted);
        $this->view->assign('arrAllAtValSorted', $arrAllAtValSorted);
        $this->view->assign('arrayCartSorted', $arrayCartSorted);

        /**
         * Get billing and shipping info
        **/
        $auth = Zend_Auth::getInstance();
        $user = $auth->getIdentity();

        $customer = null;
        if($user){
            $customer = $customerDao->getCustomer($user->user_id);
        }
        $this->view->assign('user', $user);
        $this->view->assign('customer', $customer);

        /**
         * Check all information before submit
        **/
        $is_login = false;
        if($user){
            $is_login = true;
        }

        $is_full = true;
        $arrBillAShip = array('customer_address','customer_city','customer_tel','shipping_name','shipping_email','shipping_address','shipping_city','shipping_tel');
        foreach($arrBillAShip as $row){
            if($customer){
                if($customer->$row == ''){
                    $is_full = false;
                    break;
                }
            }else{
            	$is_full = false;
            }
        }
        $this->view->assign('is_login', $is_login);
        $this->view->assign('is_full', $is_full);
        
        if($request->isPost()){
        	        	
        	/**
        	 * Kiểm tra số lượng sản phẩm trong cart vượt quá số lượng sản phẩm hiện có trong database
        	 * trước khi insert vào database
        	 * @author quanvo
        	 */            	
        	foreach($cartDetails as $d_cart){
	            $product = null;
	            if(is_numeric($d_cart->product_id)){
	                $product = $cartDao->getProductById($d_cart->product_id);
	                $itemRow = $arrPQty[$d_cart->product_id];
	        		if($product->product_quantity_mode != 'infinity' && $product->product_quantity < $itemRow){
						$this->_helper->getHelper('FlashMessenger')
                                ->addMessage($this->view->translator('review_cart_error'));
			            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_list'));        			
	        		}
	            }
	        }	        
        	
            foreach($arrayEnterpriseId as $r_Item){
                $payment_method = $request->getPost('payment_method_'.$r_Item);
                $reception_method = $request->getPost('reception_method_'.$r_Item);
                
	            if($reception_method != "home_delivery")
	            {
	            	$shipping_priceSorted[$r_Item] = 0;
	            }
	            
                $customer_notice = $request->getPost('cart_notice_'.$r_Item);

                $invoicenumber = time();
                $data = new Shop_Models_Order(array(
                        'order_status'                  => 'valid',
                        'order_edited'                  => 0,
                        'order_created_date'            => date('Y-m-d H:i:s'),
                        'customer_id'                   => $user->user_id,
                        'process_id'                    => 8,
                        'order_total_amount'            => $subtotalSorted[$r_Item],
                        'order_total_amount_currency'   => $arrayEnterpriseInfo[$r_Item]->currency,
                        'order_total_shipping_price'    => $shipping_priceSorted[$r_Item],
                        'order_invoice'                 => $invoicenumber,
                        'account_id'                    => 1,
                        'enterprise_id'                 => $r_Item,
                        'payment_method'                => $payment_method,
                        'customer_notice'               => $customer_notice,
                        'reception_method'                => $reception_method
                ));
                
                //$order_id = 100;
                $order_id = $orderDao->add($data);

                /**
                 * Update order invoice
                **/
                $numRan = substr($order_id, -3);
                $dataInvoice = array(
                    'order_id' => $order_id,
                    'order_invoice' => $invoicenumber.'_'.$numRan
                );
                $orderDao->updateInvoice($dataInvoice);

                /**
                 * Mail cart
                **/
                $order_detail = '<table width="100%" border="0" cellpadding="5" cellspacing="" style="padding: 10px;">
                                    <tr class="caption">
                                        <td width="20%">'.$this->view->translator('cart_item_image').'</td>
                                        <td width="25%">'.$this->view->translator('cart_item_name').'</td>
                                        <td width="20%">'.$this->view->translator('cart_item_price').'</td>
                                        <td width="15%">'.$this->view->translator('cart_item_quantity').'</td>
                                        <td width="20%">'.$this->view->translator('cart_item_subtotal').'</td>
                                    </tr>';

                /**
                 * Add order detail
                **/
                $arrProductsInfo = $arrProductsSorted[$r_Item];
                $enterpriseInfo = $arrayEnterpriseInfo[$r_Item];
                
                foreach($arrayCartSorted[$r_Item] as $cart_R){
                    $arrSubProductsInfo = $arrProductsInfo[$cart_R->id];
                    $dataDetail = array(
                            'order_id'                      => @$order_id,
                            'product_id'                    => $cart_R->product_id,
                            'order_detail_product_price'    => $arrSubProductsInfo['p_price'],
                            'order_detail_currency'         => $arrSubProductsInfo['p_currency'],
                            'order_detail_quantity'         => $cart_R->cart_quantity,
                            'product_value_type_id_chain'   => $cart_R->product_attribute_value_id_chain,
                            'order_detail_parent_id'        => $cart_R->cart_parent_id,
                            'order_detail_commission'       => null
                        );

                   	//$idDetail = 140;
                    $idDetail = $orderDao->addDetail($dataDetail);

                    /**
                    * Item info for mail
                    **/
                    $order_detail .='<tr>
                                        <td>';
                                        $order_detail .= ($arrSubProductsInfo['p_image'])?"<img src=\"{$arrSubProductsInfo['p_image']}\" />":'&nbsp;';

                    $order_detail .=    '</td><td>'.$arrSubProductsInfo['p_name'];

                    $order_detail .=    '</td><td>'.$arrSubProductsInfo['p_price'].' '.$arrSubProductsInfo['p_currency'];

                    $order_detail .=    '</td><td>'.$cart_R->cart_quantity;

                    $order_detail .=    '</td><td>'.$arrSubProductsInfo['total_price'].' '.$arrSubProductsInfo['p_currency'];

                    $order_detail .=    '</td>
                                    </tr>';
                }
                $order_detail .= '</table>';

                $totalAmount = $subtotalSorted[$r_Item]+$shipping_priceSorted[$r_Item];
                $order_summary = "<div>{$this->view->translator('cart_subtotal_amount')}: ".$subtotalSorted[$r_Item].' '.$arrayEnterpriseInfo[$r_Item]->currency."</div>";
                $order_summary .= "<div>{$this->view->translator('cart_shipping_amount')}: ".$shipping_priceSorted[$r_Item].' '.$arrayEnterpriseInfo[$r_Item]->currency."</div>";
                $order_summary .= "<div>{$this->view->translator('cart_total_amount')}: ".$totalAmount.' '.$arrayEnterpriseInfo[$r_Item]->currency."</div>";

               /**
				* Send email order
				*/
                $mailContent = $order_detail.$order_summary;

                $from = "admin@kinhdoanhdientu.com";
                $from_name = "kinhdoanhdientu.vn";
                $to = "{$user->email};{$enterpriseInfo->contact_email}";
                //$to = "{$user->email}";
                $bcc = "quan.vo@startech.vn";
                $content = $mailContent;
                $subject = "Welcome to kinhdoanhdientu.vn";
                $transport = Mail_Services_Mailer::getMailTransport();
                $mail = new Zend_Mail('utf-8');
                $mail->setFrom($from, $from_name)
                    ->addTo($to)
                    ->addBcc($bcc)
                    ->setSubject($subject)
                    ->setBodyHtml($content)
                    ->send($transport);
            }

            /**
             * Remove cart from table temp
            **/
            $cartDao->delete($card_id);

            /**
             * Redirect
            **/
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'shoppingcart_shoppingcart_result'));
        }
    }

    public function resultAction(){

    }

    /**
     * Remove cart form shopping cart with date_created+2 < current_date
    **/
    public function removeCartAction(){
    	$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        
        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);

        $int_date = time()-($this->_timeChecked);
        $date = date('Y-m-d',$int_date);
        $carts = $cartDao->getCBD($date);
        foreach($carts as $cart){
            $cartDao->delete($cart->cart_id);
        }
        
        $this->getResponse()->setBody('Successfully!');
    }

    /**=======================Fucntion=========================*/
    /**
     * Auto create password
    **/
    public function generatePassword($length=9, $strength=0) {
        $vowels = 'aeuy';
        $consonants = 'bdghjmnpqrstvz';
        if ($strength & 1) {
            $consonants .= 'BDGHJLMNPQRSTVWXZ';
        }
        if ($strength & 2) {
            $vowels .= "AEUY";
        }
        if ($strength & 4) {
            $consonants .= '23456789';
        }
        if ($strength & 8) {
            $consonants .= '@#$%';
        }

        $password = '';
        $alt = time() % 2;
        for ($i = 0; $i < $length; $i++) {
            if ($alt == 1) {
                $password .= $consonants[(rand() % strlen($consonants))];
                $alt = 0;
            } else {
                $password .= $vowels[(rand() % strlen($vowels))];
                $alt = 1;
            }
        }
        return $password;
    }

    /**
     * Build cookie
     * Return cart_id
     * @return int
    **/
    public function buildCookie(){
        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);

        if(!isset($_COOKIE['cart_cookie'])){
            /**
             * Get all cart
             * $arrCarts : Array cart id
            **/
            $carts = $cartDao->getCart();
            $arrCarts = array();
            foreach($carts as $c_row){
                $arrCarts[] = $c_row->cart_id;
            }

            /**
             * Create array 1 element to compare $arrCarts
             * Return $arrDiff : array 1 element is cart_id new
             **/
            while(true){
                $arrNumRand = array(rand(1,2147483647));
                $arrDiff = array_diff($arrNumRand, $arrCarts);
                if($arrDiff){
                    break;
                }
            }
            $cart_id = $arrDiff[0];
            $created_date = date('Y-m-d');
            $cart = new Shoppingcart_Models_Cart(array(
                        'cart_id'      => $cart_id,
                        'created_date' => $created_date,
            ));
            $bool = $cartDao->add($cart);

            /**
            * Set cookie new value if add cart success
            **/
            if($bool){
                setcookie('cart_cookie', $cart_id, time()+$this->_timeChecked, '/');
            }
        }else{
            $cart_id = $_COOKIE['cart_cookie'];

            /**
             * Check $cart_id isset database
             * If not exist in database: Add to database and set new cookie
            **/
            $cart = $cartDao->getById($cart_id);
            if(!$cart){
                $cart_id = $cart_id;
                $created_date = date('Y-m-d');
                $cart = new Shoppingcart_Models_Cart(array(
                            'cart_id'      => $cart_id,
                            'created_date' => $created_date,
                ));
                $bool = $cartDao->add($cart);

                /**
                * Set cookie new value if add cart success
                **/
                if($bool){
                    setcookie('cart_cookie', $cart_id, time()+$this->_timeChecked, '/');
                }
            }else{
                if(isset($_SESSION['time_for_update'])){
                    $time_for_update = $_SESSION['time_for_update'];
                    if(time() - $time_for_update >= 3600){
                        /**
                        * Update date active for cart_id
                        **/
                        $created_date = date('Y-m-d');
                        $cart = new Shoppingcart_Models_Cart(array(
                                    'cart_id'      => $cart_id,
                                    'created_date' => $created_date,
                        ));
                        $returnId = $cartDao->update($cart);

                        $_SESSION['time_for_update'] = time();
                    }
                }else{
                    $_SESSION['time_for_update'] = time();
                }
            }
        }
        return $cart_id;
    }
}